<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseAdminController;
use App\Http\Requests\TrainingLevelContentRequest;
use App\Models\QueryBuilder;
use App\Models\TrainingLevelContent;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Spatie\QueryBuilder\AllowedFilter;

class TrainingLevelContentController extends BaseAdminController
{
    //列表
    public function index()
    {
        $data = QueryBuilder::for(TrainingLevelContent::query())
            ->fields()
            ->filters([AllowedFilter::exact('training_level_head_id'), 'question', 'code_example'])
            ->includes('trainingLevelHead.trainingLevel')
            ->sorts()
            ->page();
        return $this->success(JsonResource::collection($data));
    }

    //添加
    public function store(TrainingLevelContentRequest $request)
    {
        $data = $request->toArray();
        TrainingLevelContent::query()->create($data);
        return $this->success();
        return $this->success();
    }

    //编辑
    public function update(TrainingLevelContent $traininglevelcontent, TrainingLevelContentRequest $request)
    {
        $traininglevelcontent->update($request->toArray());
        return $this->success();
    }

    //删除
    public function destroy(TrainingLevelContent $traininglevelcontent)
    {
        $traininglevelcontent->delete();
        return $this->noContent();
    }

    //执行PHP代码
    public function editCode(Request $request)
    {
        $content = $request->get('content');

        $file_name = (string) Str::uuid() . "@" . date("YmdH", time());
        Storage::deleteDirectory("code");
        Storage::put("code/" . $file_name . ".php", $content);

        $file = storage_path("app/code/" . $file_name . ".php");

        try {
            require $file;
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
    }
}
